package com.yh.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yh.javabean.Product;
import com.yh.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/product")
public class ProductController {


    @Autowired
    ProductService productService;

    @RequestMapping("/findAll")
    public String findAll(@RequestParam(value = "page",required = false,defaultValue = "1") int page,
                          @RequestParam(value = "size",required = false,defaultValue = "5")int limit,
                          HttpServletRequest request){

        PageHelper.startPage(page,limit);
        List<Product> all = productService.findAll();
        PageInfo<Product> pageInfo=new PageInfo<>(all);
        request.setAttribute("pageInfo",pageInfo);
        return "/product/product-list";
    }


    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public String save(Product product){
        boolean b = productService.saveProduct(product);
        return "redirect:findAll";
    }

    @GetMapping("/editById")
    public String editById(int id ,HttpServletRequest request){
        Product product =  this.productService.findById(id);
        request.setAttribute("product",product);
        return "/product/product-edit";
    }

    @PostMapping("/edit")
    public String edit(Product product){
        productService.editProduct(product);
        return "redirect:findAll";
    }

    @GetMapping("/deleteById")
    public String deleteById(int id ){
        productService.deleteProduct(id);
        return "redirect:findAll";
    }
    //产品详情
    @GetMapping("/findById")
    public String findById(int id ,HttpServletRequest request){
        Product byId = productService.findById(id);
        request.setAttribute("product",byId);

        return "/product/product-show";
    }

    //批量删除
    @PostMapping("selectDelete")
    public String selectDelete(@RequestParam("ids") int[] ids){
        for (int id : ids) {
            System.out.println(id);
            this.productService.deleteProduct(id);
        }
        return "redirect:findAll";
    }

}
